package com.fenghuajueli.libbasecoreui.ui;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.blankj.utilcode.util.ClipboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.fenghuajueli.libbasecoreui.baseswitch.SwitchKeyUtils;
import com.fenghuajueli.libbasecoreui.databinding.ActivityCustomerServiceBinding;
import com.fenghuajueli.libbasecoreui.mvp.BaseActivity;
import com.fenghuajueli.libbasecoreui.user.UserInfoUtils;
import com.fenghuajueli.libbasecoreui.widget.ProgressWebview;
import com.tbruyelle.rxpermissions2.RxPermissions;

import io.reactivex.disposables.Disposable;

/**
 * 联系客服界面
 */
public class CustomerServiceActivity extends BaseActivity {

    public static void start(Context context) {
        Intent intent = new Intent(context, CustomerServiceActivity.class);
        context.startActivity(intent);
    }

    private ActivityCustomerServiceBinding binding;

    private RxPermissions rxPermissions = new RxPermissions(this);
    private Disposable disposable;

    private ValueCallback<Uri[]> uploadFileData;
    private String paramterValue = "";

    private ActivityResultLauncher<Intent> intentActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    try {
                        if (uploadFileData != null) {
                            if (result != null && result.getData() != null) {
                                Uri uri = result.getData().getData();
                                if (uri != null) {
                                    uploadFileData.onReceiveValue(new Uri[]{uri});
                                } else {
                                    uploadFileData.onReceiveValue(null);
                                }
                            } else {
                                uploadFileData.onReceiveValue(null);
                                uploadFileData = null;
                            }
                        }
                    } catch (Exception e) {
                        ToastUtils.showShort("文件上传失败！");
                    }
                }
            });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityCustomerServiceBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.webView.setWebViewListener(new ProgressWebview.WebViewListener() {
            @Override
            public void openFile(ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                applyPermission(filePathCallback, fileChooserParams);
            }
        });
        String serverUrl = SwitchKeyUtils.getMQServerUrl();
        if (TextUtils.isEmpty(serverUrl)) {
            binding.webView.setVisibility(View.GONE);
            binding.tvServerQQ.setText("客服QQ：" + SwitchKeyUtils.getServiceQQ());
            binding.tvServerDesc.setVisibility(View.VISIBLE);
            binding.tvServerQQ.setVisibility(View.VISIBLE);
            //设置客服qq相关信息
            binding.tvServerQQ.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ClipboardUtils.copyText(SwitchKeyUtils.getServiceQQ());
                    ToastUtils.showShort("复制成功!");
                }
            });
        } else {
            binding.webView.setVisibility(View.VISIBLE);
            binding.tvServerDesc.setVisibility(View.GONE);
            binding.tvServerQQ.setVisibility(View.GONE);
            String userId = "";
            String vipCode = "";
            if (UserInfoUtils.getInstance().isLogin()) {
                userId = String.valueOf(UserInfoUtils.getInstance().getUserInfoEntity().getUserInfo().getUser_id());
                vipCode = UserInfoUtils.getInstance().getUserInfoEntity().getUserInfo().getShare_id();
            }
            paramterValue = "&metadata=" + "{\"name\":\"" + userId + "\",\"address\":\"" + vipCode + "\"}";
            binding.webView.loadUrl(serverUrl + paramterValue);
        }
    }

    private void applyPermission(ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (rxPermissions.isGranted(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                selectPhoto(filePathCallback, fileChooserParams);
            } else {
                disposable = rxPermissions
                        .request(
                                Manifest.permission.READ_EXTERNAL_STORAGE
                        ).subscribe(granted -> {
                            if (granted) {
                                selectPhoto(filePathCallback, fileChooserParams);
                            }
                        });
            }
        } else {
            selectPhoto(filePathCallback, fileChooserParams);
        }
    }


    @Override
    public void onBackPressed() {
        if (binding.webView.canGoBack()) {
            binding.webView.goBack();
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (disposable != null) {
            disposable.dispose();
        }
    }

    private void selectPhoto(ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
        if (fileChooserParams.getAcceptTypes() != null && fileChooserParams.getAcceptTypes().length > 0) {
            LogUtils.json(fileChooserParams.getAcceptTypes());
            uploadFileData = filePathCallback;
            String mediaType = fileChooserParams.getAcceptTypes()[0];
            if ("".equals(mediaType)) {
                mediaType = "*/*";
            }
            LogUtils.d("选择文件的类型为：" + mediaType);
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType(mediaType);
            intentActivityResultLauncher.launch(Intent.createChooser(intent, "请选择文件"));
        } else {
            ToastUtils.showShort("未指定上传文件的类型！");
            uploadFileData = null;
        }
    }


}